package control;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import beans.LoginInfo;

import dataaccess.CarDB;
import dataaccess.UsersDB;
import domain.CarList;
import domain.User;

public class LoginAction extends HttpServlet {
	boolean followForward = true;// flag used to make sure the page only
									// forwards the request once
	UsersDB udb = new UsersDB();// connects to the users database

	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {

		doPost(request, response);

	}

	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		HttpSession session = request.getSession();
		checkCookieAndRedirect(request, response);

		// if the login bean does not exist create a new LoginBean, and forward
		// request to LoginPage.jsp

		if (session.getAttribute("login") == null) {

			session.setAttribute("login", new LoginInfo());
			if (followForward) {
				System.out.println("forwarding to LoginPage.jsp");
				getServletConfig().getServletContext()
						.getRequestDispatcher("/LoginPage.jsp")
						.forward(request, response);
				followForward = false;
			}

		} else {

			// if the LoginInfo exists this means the client came to the page
			// from the login page
			// we set the parameter values, check user information and forward
			// afterwards
			if (followForward) {
				LoginInfo login;
				login = (LoginInfo) session.getAttribute("login");
				System.out.println("login info object created");

				setBeanValues(request, login);

				forwardToWelcomePage(request, response, login);
			}
		}
		followForward = true;

		System.out.println("-------------end run------------");
	}

	private void forwardToWelcomePage(HttpServletRequest request,
			HttpServletResponse response, LoginInfo login)
			throws ServletException, IOException {
		if (login.isComplete()) {
			System.out.println("login info is complete");

			User user = new User();
			user.setUserName(login.getName());
			user.setPassword(login.getPassword());
			if (login.isRemember() && !isUserInfoInCookie(request)) {
				createCookie(request, response, login);
			}
			HttpSession session = request.getSession();

			System.out.println("Trying to check the user info");

			if (udb.checkLogin(user)) {

				if (followForward) {
					System.out
							.println("information checked successfully ! -- redirecting to welcome page");
					session.removeAttribute("login");// the login bean is no
														// longer necessary
														// after the user info
														// has been stored
														// inside the session
					getServletConfig().getServletContext()
							.getRequestDispatcher("/WelcomePage.jsp")
							.forward(request, response);
					followForward = false;
				}

			} else {// in the case when the login information is wrong
					// we need to redisplay the login page
				if (followForward) {
					System.out
							.println("user data incorrect -- forwarding to LoginPage.jsp and removing previous values");
					
					getServletConfig().getServletContext()
							.getRequestDispatcher("/LoginPage.jsp")
							.forward(request, response);
					session.removeAttribute("userinfo");
					followForward = false;

				}
			}
		} else {// in the case when the login information is not complete
				// we need to redisplay the login page
			if (followForward) {
				System.out
						.println("user data not complete -- forwarding to LoginPage.jsp ");

				getServletConfig().getServletContext()
						.getRequestDispatcher("/LoginPage.jsp")
						.forward(request, response);
				followForward = false;

			}
		}
	}

	private void createCookie(HttpServletRequest request,
			HttpServletResponse response, LoginInfo login) {

		// if the "remember me" is checked and cookie does not exist we
		// create a cookie called userinfocookie to hold the login
		// information
		System.out
				.println("remember checked -- creating a new cookie to hold the username and password data");
		Cookie c = new Cookie("userinfocookie", login.getName() + "-"
				+ login.getPassword());
		c.setMaxAge(360);
		response.addCookie(c);

		System.out.println("Cookie created:" + request.getCookies().toString());

	}

	private void checkCookieAndRedirect(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		if (isUserInfoInCookie(request)) {
			getUserInfoFromCookie(request);
			HttpSession session = request.getSession();

			User user;
			user = (User) session.getAttribute("userinfo");
			
				if (user != null&&udb.checkLogin(user)) {

					if (followForward) {
						System.out
								.println("information checked successfully ! -- redirecting to welcome page from cookie");
						session.removeAttribute("login");// the login bean is no
															// longer necessary
															// after the user
															// info
															// has been stored
															// inside the
															// session

						getServletConfig().getServletContext()
								.getRequestDispatcher("/WelcomePage.jsp")
								.forward(request, response);
						followForward = false;
					}

				}
			
		}
	}

	private void setBeanValues(HttpServletRequest request, LoginInfo login) {
		String name = request.getParameter("name");
		if ((name != null) && (!name.trim().equals(""))) {
			login.setName(name);
		}
		String password = request.getParameter("password");
		if ((password != null) && (!password.trim().equals(""))) {
			login.setPassword(password);
		}

		String remember = request.getParameter("remember");
		System.out.println("remember me recieved parameter value:"
				+ request.getParameter("remember"));
		if ((remember != null) && (!remember.trim().equals(""))) {
			login.setRemember(true);
		}
		System.out.println("remember me bean value:" + login.isRemember());

		System.out.println("the login data is now:" + login.toString());
	}

	private void getUserInfoFromCookie(HttpServletRequest request) {
		HttpSession session = request.getSession();

		Cookie[] cookies = request.getCookies();
		if (cookies != null) {
			for (int i = 0; i < cookies.length; i++) {
				Cookie c = cookies[i];
				if (c.getName().equals("userinfocookie")) {
					String[] userinfo = c.getValue().split("-");
					User user = new User();
					user.setUserName(userinfo[0]);
					user.setPassword(userinfo[1]);
					session.setAttribute("userinfo", user);
					session.removeAttribute("login");
					System.out.println("user info cookie found" + c.getValue());

				}
			}

		}

	}

	/** checks whether the client has a user info cookie stored **/
	private boolean isUserInfoInCookie(HttpServletRequest request) {
		Cookie[] cookies = request.getCookies();
		if (cookies != null) {
			for (int i = 0; i < cookies.length; i++) {
				Cookie c = cookies[i];
				if (c.getName().equals("userinfocookie")) {
					System.out.println("cookie found");
					return true;
				}
			}

		}
		System.out.println("cookie not found");

		return false;
	}
}
